<template>
  <div class="rank-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>榜单管理</h2>
    </div>

      <!-- 操作栏 -->
      <div class="operation-bar">
        <!-- 搜索框 -->
        <div class="search-box">
          <el-input
            v-model="searchForm.keyword"
            placeholder="请输入榜单名称"
            clearable
            @keyup.enter="handleSearch"
          >
            <template #append>
              <el-button :icon="Search" @click="handleSearch" />
            </template>
          </el-input>
        </div>

        <!-- 操作按钮 -->
        <div class="action-buttons">
          <el-button type="primary" :icon="Plus" @click="handleAddRank">
            新增榜单
          </el-button>
          <el-button type="danger" :icon="Delete" @click="handleBatchDelete" :disabled="selectedRanks.length === 0">
            批量删除
          </el-button>
        </div>
      </div>

      <!-- 排行榜列表 -->
      <el-table
          :data="rankList"
          style="width: 100%"
          v-loading="loading"
          element-loading-text="加载中..."
          @selection-change="handleSelectionChange"
          border
          >
        <!-- 选择列 -->
        <el-table-column type="selection" width="55" />

        <!-- 榜单ID -->
        <el-table-column prop="rankId" label="rankId" width="80" />

        <!-- 榜单图片 -->
        <el-table-column label="排行榜图片" width="120">
          <template #default="scope">
            <div class="rank-picture">
              <el-image
                :src="getRankImageUrl(scope.row.rankPic)"
                class="picture-img"
                fit="cover"
                :preview-src-list="[getRankImageUrl(scope.row.rankPic)]"
                preview-teleported
              >
                <template #error>
                  <div class="image-slot">
                    <el-icon><Picture /></el-icon>
                  </div>
                </template>
              </el-image>
              <el-button
                type="primary"
                link
                icon="Upload"
                @click="handleUpdatePicture(scope.row)"
                class="update-picture-btn"
              >
                更新
              </el-button>
            </div>
          </template>
        </el-table-column>

        <!-- 榜单名称 -->
        <el-table-column prop="rankTitle" label="排行榜名称" />

        <!-- 简介 -->
        <el-table-column prop="rankIntro" label="简介" show-overflow-tooltip />

        <!-- 操作 -->
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button
                type="primary"
                link
                :icon="Edit"
                @click="handleEditRank(scope.row)"
            >
              编辑
            </el-button>
            <el-button
                type="primary"
                link
                :icon="Headset"
                @click="handleViewRankSongs(scope.row)"
            >
              榜单歌曲
            </el-button>
            <el-button
                type="danger"
                link
                :icon="Delete"
                @click="handleDeleteRank(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>


    <!-- 新增/编辑排行榜对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="500px"
      @close="handleDialogClose"
    >
      <el-form
          :model="rankForm"
          :rules="rankRules"
          ref="rankFormRef"
          label-width="100px"
      >
        <el-form-item label="排行榜名称" prop="rankTitle">
          <el-input v-model="rankForm.rankTitle" placeholder="请输入排行榜名称" />
        </el-form-item>

        <el-form-item label="简介" prop="rankIntro">
          <el-input
            v-model="rankForm.rankIntro"
            type="textarea"
            :rows="3"
            placeholder="请输入排行榜简介"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitRankForm" :loading="submitLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog
      title="榜单图片"
      v-model="pictureDialogVisible"
      width="400px"
      >
      <div class="picture-upload-container">
        <el-upload
          class="picture-uploader"
           drag
          :action="uploadPictureUrl"
          :headers="uploadHeaders"
          :data="{ id: currentRank?.rankId }"
          :show-file-list="false"
          :on-success="handlePictureSuccess"
          :on-error="handlePictureError"
          :before-upload="beforePictureUpload"
        >
          <el-icon class="picture-uploader-icon"><Plus /></el-icon>
          <div class="el-upload__text">
            将文件拖到此处，或<em>点击上传</em>
          </div>
          <template #tip>
            <div class="el-upload__tip">
              只能上传jpg/png文件，且不超过2MB
            </div>
          </template>
        </el-upload>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {Search, Plus, Delete, Edit, Headset, Upload, Picture} from '@element-plus/icons-vue'
import api from '@/services/api'
import rankDefaultImage from "@/assets/img/rank-default.png"
import { useRouter } from 'vue-router'


export default {
  name: 'Rank',
  component:{
    Search,
    Plus,
    Delete,
    Edit,
    Headset,
    Upload,
    Picture
  },
  setup() {
    // 加载状态
    const loading = ref(false)
    const submitLoading = ref(false)

    // 路由
    const router = useRouter()
    
    // 搜索表单
    const searchForm = reactive({
      keyword: ''
    })
    
    // 排行榜列表
    const rankList = ref([])

    //选择的排行榜
    const selectedRanks = ref([])
    
    // 分页信息
    const pagination = reactive({
      currentPage: 1,
      pageSize: 5,
      total: 0
    })
    
    // 对话框相关
    const dialogVisible = ref(false)
    const dialogTitle = ref('')
    const isEdit = ref(false)

    // 图片上传对话框
    const pictureDialogVisible = ref(false)
    const currentRank = ref(null)
    
    // 排行榜表单
    const rankForm = reactive({
      rankId: null,
      rankTitle: '',
      rankPic: '',
      rankIntro: ''
    })
    
    // 表单验证规则
    const rankRules = {
      rankTitle: [
        { required: true, message: '请输入排行榜名称', trigger: 'blur' }
      ]
    }
    
    // 表单引用
    const rankFormRef = ref(null)
    
    // 图片上传
    const defaultPicture = rankDefaultImage
    
    // 上传相关配置
    const uploadPictureUrl = '/api/rank/rankOfPic'
    const uploadHeaders = {
      Authorization: localStorage.getItem('adminToken')
    }
    
    // 获取排行榜列表
    const fetchRankList = async () => {
      loading.value = true
      try {
        let response
        if (searchForm.keyword) {
          // 搜索
          response = await api.rank.search(searchForm.keyword)
        } else {
          // 获取所有排行榜（分页）
          response = await api.rank.getAll({
            page: pagination.currentPage,
            size: pagination.pageSize
          })
        }
        
        if (response.code === '1') {
          rankList.value = response.data.list || response.data
          pagination.total = response.data.total || response.data.length
        }else{
          ElMessage.error(response.msg || '获取排行榜列表失败')
          rankList.value = []
          pagination.total = 0
        }
      } catch (error) {
        ElMessage.error('获取排行榜列表失败')
        console.error('Fetch rank list error:',error)
      } finally {
        loading.value = false
      }
    }
    
    // 处理搜索排行榜
    const handleSearch = () => {
      pagination.currentPage = 1
      fetchRankList()
    }
    
    // 处理 选中排行榜
    const handleSelectionChange = (selection) => {
      selectedRanks.value = selection
    }
    
    // 处理分页大小变化
    const handleSizeChange = (val) => {
      pagination.pageSize = val
      pagination.currentPage = 1
      fetchRankList()
    }
    
    // 处理分页页码变化
    const handleCurrentChange = (val) => {
      pagination.currentPage = val
      fetchRankList()
    }
    
    // 重置搜索
    const resetSearch = () => {
      searchForm.keyword = ''
      pagination.currentPage = 1
      fetchRankList()
    }
    
    // 处理新增榜单
    const handleAddRank = () => {
      dialogTitle.value = '新增排行榜'
      isEdit.value = false
      // 重置表单
      Object.assign(rankForm, {
        rankId: null,
        rankTitle: '',
        rankIntro: ''
      })
      dialogVisible.value = true
    }
    
    // 处理编辑
    const handleEditRank = (row) => {
      dialogTitle.value = '编辑排行榜'
      isEdit.value = true
      // 填充表单数据
      Object.assign(rankForm, {
        rankId: row.rankId,
        rankTitle: row.rankTitle,
        rankIntro: row.rankIntro
      })
      dialogVisible.value = true
    }
    
    // 处理查看歌曲
    const handleViewRankSongs = (row) => {
      // 跳转到排行榜歌曲管理页面
      router.push({
        path: '/rankSong',
        query: { rankId: row.rankId}
      })
    }
    
    // 处理删除
    const handleDeleteRank = async (row) => {
      try{
        await ElMessageBox.confirm(
            `确定要删除榜单 “${row.rankTitle}” 吗？`,
            '提示',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }
        )
        
        const response = await api.rank.delete(row.rankId)
        if (response.code === '1'){
          ElMessage.success('删除成功')
          await fetchRankList()
        } else {
          ElMessage.error(response.msg || '删除失败')
        }
      }catch (error){
        if(error !== 'cancel'){
          ElMessage.error('删除失败')
        }
      }
    }
    
    // 处理批量删除
    const handleBatchDelete = async () => {
      if(selectedRanks.value.length === 0){
        ElMessage.warning('请选择要删除的榜单')
        return
      }
      
      try {
        await ElMessageBox.confirm(
            `确定要删除 ${selectedRanks.value.length} 个榜单吗？`,
            '提示',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }
        )
        
        // 批量删除
        const deletePromises = selectedRanks.value.map(rank => 
            api.rank.delete(rank.rankId)
        )
        
        const results = await Promise.all(deletePromises)
        const successCount = results.filter(result => result.code === '1').length
        
        if (successCount > 0) {
          ElMessage.success(`成功删除 ${successCount} 个榜单`)
          await fetchRankList()
        } else {
          ElMessage.error('删除失败')
        }
      }catch ( error){
        if(error !== 'cancel')
          ElMessage.error('删除失败')
      }
    }
    
    // 处理更新图片
    const handleUpdatePicture = (row) => {
      currentRank.value = row
      pictureDialogVisible.value = true
    }
    
    // 图片上传前的处理
    const beforePictureUpload = (file) => {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2
      
      if (!isJPG) {
        ElMessage.error('图片只能是 JPG 或 PNG 格式!')
      }
      if (!isLt2M) {
        ElMessage.error('图片大小不能超过 2MB!')
      }
      
      return isJPG && isLt2M
    }
    
    // 图片上传成功处理
    const handlePictureSuccess = (response) => { 
      if(response.code === '1'){
        ElMessage.success('图片更新成功')
        pictureDialogVisible.value = false
        fetchRankList()
      } else {
        ElMessage.error(response.msg || '图片更新失败')
      }
    }
    
    // 图片上传失败处理
    const handlePictureError = (error) => {
      ElMessage.error('图片上传失败')
      console.error('Image upload error:', error)
    }
    
    const getRankImageUrl = (imagePath) => {
      
      if(!imagePath) return defaultPicture
      
      if(imagePath.startsWith('http')){
        return imagePath
      }
      
      if(imagePath.startsWith('/')){
        return imagePath
      }
      
      if(imagePath.startsWith('img/')){
        return `/${imagePath}`
      }
      
      return defaultPicture
    }
    
    // 提交排行榜
    const submitRankForm = async () => {
      if (!rankFormRef.value) return

      await rankFormRef.value.validate(async (valid) => {
        if (valid) {

          console.log('Form validation passed, rankForm:',rankForm)

          if (!rankForm.rankTitle){
            ElMessage.error('请填写排行榜名称')
            return
          }

          submitLoading.value = true
          try {
            let response
            if (isEdit.value) {

              if(!rankForm.rankId){
                ElMessage.error('请选择要编辑的排行榜')
                submitLoading.value = false
                return
              }
              // 编辑榜单
              const formData = {
                rankId: rankForm.rankId,
                rankTitle: rankForm.rankTitle,
                rankIntro: rankForm.rankIntro
              }
              console.log('Sending update data: ', formData)
              response = await api.rank.update(formData)
            } else {
              // 新增
              response = await api.rank.add({
                rankTitle: rankForm.rankTitle,
                rankIntro: rankForm.rankIntro
              })
            }
            
            if (response.code === '1') {
              ElMessage.success(isEdit.value ? '编辑成功' : '新增成功')
              dialogVisible.value = false
              await fetchRankList()
            } else {
              ElMessage.error(response?.msg || (isEdit.value ? '编辑失败' : '新增失败'))
            }
          } catch (error) {
            ElMessage.error(isEdit.value ? '编辑失败' :'操作失败')
            console.error('Submit rank form error:',error)
          }finally {
            submitLoading.value = false
          }
        }
      })
    }
    
    // 关闭对话框
    const handleDialogClose = () => {
      if(rankFormRef.value){
        rankFormRef.value.resetFields()
      }
    }
    
    // 组件挂载时获取数据
    onMounted(() => {
      fetchRankList()
    })
    
    return {
      loading,
      searchForm,
      submitLoading,
      rankList,
      pagination,
      dialogVisible,
      dialogTitle,
      selectedRanks,
      currentRank,
      rankForm,
      rankRules,
      rankFormRef,
      uploadPictureUrl,
      uploadHeaders,
      pictureDialogVisible,
      handleSearch,
      handleSelectionChange,
      resetSearch,
      handleAddRank,
      handleEditRank,
      handleViewRankSongs,
      handleDeleteRank,
      handleBatchDelete,
      beforePictureUpload,
      handleUpdatePicture,
      handlePictureSuccess,
      handlePictureError,
      getRankImageUrl,
      submitRankForm,
      handleDialogClose,
      handleSizeChange,
      handleCurrentChange
    }
  }
}
</script>

<style scoped>
.rank-container {
  padding: 20px;
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #333;
}

.operation-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f5f5;
  border-radius: 4px;
}

.search-box {
  width: 300px;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.rank-picture {
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.picture-img {
  width: 80px;
  height: 80px;
  border-radius: 50%;
}

.update-picture-btn {
  margin-top: 5px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.picture-upload-container {
  text-align: center;
}

.picture-uploader .picture-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  text-align: center;
  line-height: 120px;
}

.picture-uploader :deep(el-upload){
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.picture-uploader :deep(el-upload):hover{
  border-color: var(--el-color-primary);
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>